package com.omni.monitor.controller;

import com.omni.monitor.model.threadpool.ThreadPoolStats;
import com.omni.monitor.model.threadpool.ThreadPoolStrategy;
import com.omni.monitor.model.threadpool.ThreadPoolTrend;
import com.omni.monitor.plugin.threadpool.StrategyManager;
import com.omni.monitor.plugin.threadpool.ThreadPoolMonitor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 线程池监控前端接口
 */
@RestController
@RequestMapping("/api/threadpool")
@CrossOrigin(origins = "*") // 开发环境允许跨域，生产环境需指定前端域名
@Slf4j
public class ThreadPoolMonitorController {

    @Autowired
    private ThreadPoolMonitor threadPoolMonitor;

    @Autowired
    private StrategyManager strategyManager;

    /**
     * 1. 获取所有线程池最新状态
     */
    @GetMapping("/all-stats")
    public List<ThreadPoolStats> getAllPoolStats() {
        return threadPoolMonitor.getAllPoolStats();
    }

    /**
     * 2. 获取指定线程池趋势分析
     */
    @GetMapping("/trend/{poolName}")
    public ThreadPoolTrend getTrend(@PathVariable String poolName) {
        return threadPoolMonitor.getTrend(poolName);
    }

    /**
     * 3. 手动配置线程池参数
     * 请求体示例：
     * {
     *   "poolName": "order-pool",
     *   "corePoolSize": 10,
     *   "maximumPoolSize": 20,
     *   "queueCapacity": 500
     * }
     */
    @PostMapping("/config")
    public String configParams(@RequestBody Map<String, Object> params) {
        try {
            String poolName = (String) params.get("poolName");
            if (params.containsKey("corePoolSize")) {
                int core = Integer.parseInt(params.get("corePoolSize").toString());
                threadPoolMonitor.setCorePoolSize(poolName, core);
            }
            if (params.containsKey("maximumPoolSize")) {
                int max = Integer.parseInt(params.get("maximumPoolSize").toString());
                threadPoolMonitor.setMaximumPoolSize(poolName, max);
            }
            if (params.containsKey("queueCapacity")) {
                int queueCap = Integer.parseInt(params.get("queueCapacity").toString());
                threadPoolMonitor.setQueueCapacity(poolName, queueCap);
            }
            return "配置成功";
        } catch (Exception e) {
            log.error("手动配置线程池参数失败", e);
            return "配置失败：" + e.getMessage();
        }
    }

    /**
     * 4. 策略管理：获取所有策略
     */
    @GetMapping("/strategies")
    public List<ThreadPoolStrategy> getAllStrategies() {
        return strategyManager.getAllStrategies();
    }

    /**
     * 5. 策略管理：新增/更新策略
     */
    @PostMapping("/strategy/save")
    public String saveStrategy(@RequestBody ThreadPoolStrategy strategy) {
        try {
            if (strategy.getStrategyId() == null || strategyManager.getStrategyById(strategy.getStrategyId()) == null) {
                strategyManager.addStrategy(strategy);
            } else {
                strategyManager.updateStrategy(strategy);
            }
            return "策略保存成功";
        } catch (Exception e) {
            log.error("保存线程池策略失败", e);
            return "策略保存失败：" + e.getMessage();
        }
    }

    /**
     * 6. 策略管理：删除策略
     */
    @DeleteMapping("/strategy/{strategyId}")
    public String deleteStrategy(@PathVariable String strategyId) {
        try {
            strategyManager.deleteStrategy(strategyId);
            return "策略删除成功";
        } catch (Exception e) {
            log.error("删除线程池策略失败", e);
            return "策略删除失败：" + e.getMessage();
        }
    }
}